﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using SuraQR.Bean;
using SuraQR.Controller;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using SuraQR.Config;
using System.Reflection;
using SuraQR.ServerForm;
using System.Collections;

namespace SuraQR
{
    public partial class lunchersv : Form , IQRCodeEngineService
    {
        private QRCodeEngineService _QRcodeService;
        private BindingSource b, t3;

        public BindingSource T3
        {
            get { return t3; }
            set { t3 = value; }
        }

        public BindingSource B
        {
            get { return b; }
            set { b = value; }
        }

        public lunchersv()
        {
            InitializeComponent();

           /* TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
            Debug.Listeners.Add(tr1);

            TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
            Debug.Listeners.Add(tr2);
            Debug.Unindent();
            Debug.WriteLine("xx");*/

        }

        private void luncher_Load(object sender, EventArgs e)
        {
            // init data
            if (tab1AddrBlinding.List.Count == 0)
            {
                Debug.WriteLine("Addrdess new ");
                tab1AddrBlinding.AddNew();               
            }            

            // tab3
            if (tab3Tax.List.Count == 0)
            {
                tab3Tax.AddNew();
            }
           
            //staff
            if (tab1Staff.List.Count == 0)
            {
                tab1Staff.AddNew();
            }

            T3 = tab3Tax;
            this.B = tab1AddrBlinding;

            //version
            lblVersion.Text = "Version : " + SuraQR.Config.PropertiesConfig._AppVersin;

            //Load
            _QRcodeService = new QRCodeEngineService();
            string[] listName = _QRcodeService.getCOMPortList();
            
            cbb_COMP.Visible = false;
            btn_setting.Visible = false;

            if (listName.Length == 0)
            {
                MessageBox.Show("ไม่พบ อุปกรณ์ Scaner BarCode");
                rio_discon.Checked = true;
            }
            else
            {
                rio_connect.Checked = true;
                _QRcodeService.strat(listName[listName.Length - 1], this);
                ServerRuntimeSingleton.Instance.QRcodeService = _QRcodeService;

                if (listName.Length > 1)
                {
                    cbb_COMP.Visible = true;
                    btn_setting.Visible = true;
                 
                    for (int i = 0; i < listName.Length; i++)
                    {
                        cbb_COMP.Items.Add(listName[i]);
                    }

                }
            }

            // database
            ServerRuntimeSingleton.Instance.OrcleDB = new OracleDriver11g();
            ServerRuntimeSingleton.Instance.OrcleDB.init();

            Debug.Flush();
            
        }
        
        private void radioButtonCheck(RadioButton r, string v)
        {
            bool chk =  (r.Text.Equals(v)) ? true : false;
            if (chk)
                r.Checked = true;

            Debug.WriteLine("radio : " + v + " : " + r.Checked);
        }
        
        private delegate void dumpDataToFormfn(SOROR12011 dumpData);
        public void dumpDataToForm(SOROR12011 dumpData)
        {
            if (dumpData.Addr != null)
            {
                tab1AddrBlinding.List.Clear();
                tab1AddrBlinding.List.Add(dumpData.Addr);
                tab1AddrBlinding.ResetBindings(false);
            }

            if (dumpData.Straff != null)
            {
                tab1Staff.List.Clear();
                tab1Staff.List.Add(dumpData.Straff);
            }

            if (dumpData.OrderList != null)
            {/*
                tab2OrderList.List.Clear();
                foreach (Order d in dumpData.OrderList)
                {
                    tab2OrderList.List.Add(d);
                }
              */
                tab2OrderList.List.Add(dumpData.OrderList[0]);
            }

            if (dumpData.Tax != null)
            {
                tab3Tax.List.Clear();
                tab3Tax.List.Add(dumpData.Tax);

                Tax t = dumpData.Tax;
                radioButtonCheck(radioButton1, t.TaxTypeRadio);
                radioButtonCheck(radioButton2, t.TaxTypeRadio);
                radioButtonCheck(radioButton3, t.TaxTypeRadio);

            }

            // Clear and Read Again
            _QRcodeService.clearReadData();

        }

        private void setRowNumber(DataGridView dgv)
        {
            foreach (DataGridViewRow row in dgv.Rows)
            {
                row.HeaderCell.Value = (row.Index + 1).ToString();
            }
        }

        private void btnOrderEdit_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("EDIT");
            OrderDetailFrm keyInOrder = new OrderDetailFrm();
            keyInOrder.IsEdit = true;
            if (tab2OrderList.Current != null)
            {
                keyInOrder.AddNewOrder = (Order)tab2OrderList.Current;
                keyInOrder.ShowDialog();
            }
            Debug.WriteLine("edit");
        }

        private void btnOrderDel_Click(object sender, EventArgs e)
        {
            if (tab2OrderList.Current != null)
            {
                tab2OrderList.Remove(tab2OrderList.Current);
            }
        }
        
        private void btnOrderAdd_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("ADD");
            OrderDetailFrm keyInOrder = new OrderDetailFrm();
            keyInOrder.ShowDialog();
            if (keyInOrder.AddNewOrder != null)
            {
                tab2OrderList.Add(keyInOrder.AddNewOrder);
                setRowNumber(orderList);
            }

        }
      
        private void button1_Click_1(object sender, EventArgs e)
        {
            //dataMorniter m = new dataMorniter();
            //m.Lun = this;
            //m.Show();
        }

        private void radioCheckedChanged(object sender, EventArgs e)
        {
           
            if (tab3Tax.List.Count > 0)
            {
                RadioButton rd = (RadioButton)sender;
                Tax t = (Tax)tab3Tax.List[0];
                t.TaxTypeRadio = rd.Text;
            }
         
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SOROR12011 s = new SOROR12011();
            ArrayList sql = new ArrayList();

            string row_id = Guid.NewGuid().ToString();
           

            s.Addr = (F1Address)tab1AddrBlinding.List[0];
            sql.Add(SQLUtils.insertAddr(row_id, s.Addr));

            s.OrderList = new Order[tab2OrderList.List.Count];
             for(int i = 0 ; i < tab2OrderList.List.Count ; i++){
               s.OrderList[i] = (Order)tab2OrderList.List[i];
               sql.Add(SQLUtils.insertOrder(row_id, s.OrderList[i]));
            }


            s.Tax = (Tax)tab3Tax.List[0];
            sql.Add(SQLUtils.insertTax(row_id, s.Tax));

            try
            {
                ServerRuntimeSingleton.Instance.OrcleDB.transectionUpdate(sql);

                MessageBox.Show("บันทึกรายการเรียบร้อย");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void clearConfig()
        {
            _QRcodeService.close();
        }

        //QR Event
        public void onComplete(SOROR12011 data)
        {
            Debug.WriteLine("onComplete");
            dumpDataToFormfn fn1 = new dumpDataToFormfn(dumpDataToForm);
            this.Invoke(fn1, new object[] { data });
            hideProcessfn fn = new hideProcessfn(hideProcess);
            this.Invoke(fn);
            Debug.Flush();
        }

        public void onError(Exception e)
        {
            Debug.WriteLine("onError");
            disPlayErrorfn fn = new disPlayErrorfn(disPlayError);
            this.Invoke(fn, new object[] { e.ToString() });
        }

        public void onClear()
        {
            Debug.WriteLine("onClear");
            hideProcessfn fn = new hideProcessfn(hideProcess);
            this.Invoke(fn);
        }

        
        public void onFirst(int maxsize)
        {
            Debug.WriteLine("onFirst");
            QRCodeProcessHandleFn fn = new QRCodeProcessHandleFn(showFormProcess);
            this.Invoke(fn,new object[]{maxsize});
        }

        public void onReadComplate(int index,int currentSize, string msg)
        {
            Debug.WriteLine("onReadComplate : " + index + " = " + msg);
            updateProcessfn fn = new updateProcessfn(updateProcess);
            this.Invoke(fn, new object[] { currentSize ,msg});
           
        }

        private delegate void QRCodeProcessHandleFn(int max);
        private QRCodeProcessHandle _processQR = null;
        public void showFormProcess(int max){
              if (_processQR == null)
            {
                _processQR = new QRCodeProcessHandle();
                _processQR.setinitValue(max);
                _processQR.Show();
            }
            else
            {
                _processQR.setinitValue(max);
                _processQR.Show();
            }
        }

        private delegate void updateProcessfn(int curr, string msg);
        private void updateProcess(int curr, string msg)
        {
            _processQR.updateProcess(curr, msg);
        }

        private delegate void disPlayErrorfn(string msg);
        private void disPlayError(string msg)
        {
            _processQR.disPlayError(msg);
        }

        private delegate void hideProcessfn();
        private void hideProcess()
        {
            _processQR.Hide();
            _processQR.clearDisplay();
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void btn_setting_Click(object sender, EventArgs e)
        {
            _QRcodeService.close();
            rio_connect.Checked = true;
            if (cbb_COMP.SelectedItem != null)
            {
                _QRcodeService.strat((string)cbb_COMP.SelectedItem, this);
                ServerRuntimeSingleton.Instance.QRcodeService = _QRcodeService;
                MessageBox.Show("Setting " + cbb_COMP.SelectedItem + " เรียบร้อย");
            }
        }

        //end event
             


       private void calcOrderTax()
        {
            Debug.WriteLine("cal Tax");
            if (tab2OrderList.List.Count == 0)
            {
                Debug.WriteLine("No order cal in calcOrderTax");
                return;
            }

            //calc

            double sumAdTax = 0;
            double sumQty = 0;

            foreach (Order o in tab2OrderList.List)
            {
                sumAdTax += o.TotalAdValoremTax;
                sumQty += o.TotalQuantityTax;
            }

            Tax t = (Tax) tab3Tax.List[0];
            t.Data6_1 = sumAdTax;
            t.Data6_2 = sumQty;

            t.Data7 = t.Data6_1 + t.Data6_2;

            t.Data9 = t.Data7 - t.TaxRoyalReturn;
            t.Data10 = t.Data9;
            t.Data11 = (t.Data10 * t.TaxMinistryOfInterior) / 100;
            t.Data12 = t.Data10 + t.Data11;
            t.Data13 = t.Data12;
            //t.Data14 
            t.Data15 = t.Data14 + t.Data13;

            tab3Tax.ResetBindings(false);
            
        }

       private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
       {
           TabControl t = (TabControl)sender;
           Debug.WriteLine("Tab : " + t.SelectedTab.Name);
           Debug.WriteLine("Tab : " + t.SelectedIndex);
           if (t.SelectedIndex == 2)
           {
              // this.calcOrderTax();
           }
       }
    }
}
